package com.dfbz.demo01_多线程实现聊天案例;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo02_Server {
    public static void main(String[] args) throws Exception {

        // 创建一台服务器
        ServerSocket serverSocket = new ServerSocket(9999);

        // 接收一个客户端
        Socket client = serverSocket.accept();

        // 获取与这个客户端的输入输出流
        InputStream is = client.getInputStream();
        OutputStream os = client.getOutputStream();

        String hostAddress = client.getInetAddress().getHostAddress();
        int port = client.getPort();
        System.out.println("有一个客户端来连接了，地址【" + hostAddress + "】，端口【" + port + "】");


        // 读线程
        new Thread() {
            @Override
            public void run() {
                try {
                    byte[] data = new byte[1024];

                    while (true) {
                        int len = is.read(data);
                        System.out.println("接收到了来自客户端【" + hostAddress + "】的信息【" + new String(data, 0, len) + "】");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        // 写线程
        new Thread() {
            @Override
            public void run() {
                try {
                    Scanner scanner = new Scanner(System.in);
                    while (true){
                        String str = scanner.nextLine();
                        os.write(str.getBytes());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();


    }
}
